﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.UI;
using System.Web.UI.WebControls;
using Amkeni_Monitoring_Plan.Classes;
using AmkeniCrossLoginApplication.Data_Access;

namespace Amkeni_Monitoring_Plan
{
    public partial class Default : System.Web.UI.Page
    {
        Amkeni_DatabaseEntities db = new Amkeni_DatabaseEntities();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindGrid();

                IPMonitoringPlanGridView.DataSource = getIPMonitoringPlan(getIP().ToString());
                IPMonitoringPlanGridView.DataBind();
                BindIPMonitoringPlanGridView();
            }
        }

        private DataTable getIPMonitoringPlan(string ip_id)
        {
            DataTable dt = new DataTable();
            SqlConnection SQLconn = null;
            try
            {
                string strQuery = "SELECT * FROM monitoring_plan_view where ip_id = " + ip_id;
                SQLconn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
                SqlCommand SQLcmd = new SqlCommand();
                SQLcmd.CommandText = strQuery;
                SQLcmd.Connection = SQLconn;
                SQLcmd.Connection.Open();
                SqlDataAdapter sqlDa = new SqlDataAdapter(SQLcmd);
                sqlDa.Fill(dt);
                SQLconn.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return dt;
        }

        private int getIP()
        {
            int ip = 0;
            var U_IP = (from u in db.users where u.email == User.Identity.Name select new { u.ip_id }).FirstOrDefault();
            if (U_IP != null)
            {
                int ipNum;
                if (int.TryParse(U_IP.ip_id.ToString(), out ipNum))
                {
                    ip = int.Parse(U_IP.ip_id.ToString());
                }
            }
            return ip;
        }

        protected void BindIPMonitoringPlanGridView()
        {
            foreach (GridViewRow row in IPMonitoringPlanGridView.Rows)
            {
                if (row.RowType == DataControlRowType.DataRow)
                {
                    Label IDLabel = row.FindControl("IDLabel") as Label;
                    int planID = int.Parse(IDLabel.Text.Trim());

                    var freq = (from d in db.monitoring_data_collection_frequency_connector
                                where d.monitoring_plan_id == planID
                                select new
                                {
                                    d.report_period_id
                                });
                    if (freq != null)
                    {
                        foreach (var data2 in freq)
                        {
                            if (data2.report_period_id == 1)
                            {
                                CheckBox Q1 = row.FindControl("CheckBox1") as CheckBox;
                                Q1.Checked = true;
                            }
                            else if (data2.report_period_id == 2)
                            {
                                CheckBox Q2 = row.FindControl("CheckBox2") as CheckBox;
                                Q2.Checked = true;
                            }
                            else if (data2.report_period_id == 3)
                            {
                                CheckBox Q3 = row.FindControl("CheckBox3") as CheckBox;
                                Q3.Checked = true;
                            }
                            else if (data2.report_period_id == 4)
                            {
                                CheckBox Q4 = row.FindControl("CheckBox4") as CheckBox;
                                Q4.Checked = true;
                            }
                        }
                    }
                }
            }
        }

        private string ArrayToString(IEnumerable<string> strValues)
        {
            string strValue = string.Empty;
            foreach (string strVal in strValues)
            {
                strValue = strValue + "'" + strVal + "', ";
            }
            if (strValue.Length > 0)
            {
                strValue = "(" + strValue.Substring(0, strValue.Length - 2) + ")";
            }
            return strValue;
        }

        protected void Refresh_Click(object sender, EventArgs e)
        {
            BindGrid();
        }

        protected void BindGrid()
        {
            var strQuery = "SELECT * FROM monitoring_plan_view ";
            var objJavaScriptSerializer = new JavaScriptSerializer();

            SelectedDataCollection objSelectedDataCollection = new SelectedDataCollection();

            if (hndSelectedValue.Value.Trim().Length > 0)
            {
                objSelectedDataCollection = objJavaScriptSerializer.Deserialize<SelectedDataCollection>(hndSelectedValue.Value);

                foreach (SelectedData selectedData in objSelectedDataCollection.DataCollection)
                {
                    if (selectedData.SelectedValue.Count<string>() > 0)
                    {
                        strQuery = strQuery + ((strQuery.Contains(" WHERE ") == true) ? " AND " : " WHERE ") + selectedData.ColumnName + " IN " + ArrayToString(selectedData.SelectedValue);
                    }
                }
            }

            MonitoringPlanDAO objMonitoringPlanDAO = new MonitoringPlanDAO();

            IList<monitoring_plan_view> monitoringPlanList = objMonitoringPlanDAO.GetMonitoringPlans(strQuery);
            if (monitoringPlanList.Count == 0)
            {
                monitoringPlanList.Add(new monitoring_plan_view());
            }

            MonitoringGridView.DataSource = monitoringPlanList;
            MonitoringGridView.DataBind();

            foreach (GridViewRow row in MonitoringGridView.Rows)
            {
                if (row.RowType == DataControlRowType.DataRow)
                {
                    Label IDLabel = row.FindControl("IDLabel") as Label;
                    int planID = int.Parse(IDLabel.Text.Trim());

                    var freq = (from d in db.monitoring_data_collection_frequency_connector
                                where d.monitoring_plan_id == planID
                                select new
                                {
                                    d.report_period_id
                                });
                    if (freq != null)
                    {
                        foreach (var data2 in freq)
                        {
                            if (data2.report_period_id == 1)
                            {
                                CheckBox Q1 = row.FindControl("CheckBox1") as CheckBox;
                                Q1.Checked = true;
                            }
                            else if (data2.report_period_id == 2)
                            {
                                CheckBox Q2 = row.FindControl("CheckBox2") as CheckBox;
                                Q2.Checked = true;
                            }
                            else if (data2.report_period_id == 3)
                            {
                                CheckBox Q3 = row.FindControl("CheckBox3") as CheckBox;
                                Q3.Checked = true;
                            }
                            else if (data2.report_period_id == 4)
                            {
                                CheckBox Q4 = row.FindControl("CheckBox4") as CheckBox;
                                Q4.Checked = true;
                            }
                        }
                    }

                    //string ip = (from x in db.monitoring_plan
                    //             where x.monitoring_plan_id == planID
                    //             select new { x.implementing_partner.abbreviation }).First().abbreviation;
                    //Label ipLabel = row.FindControl("IPLabel") as Label;
                    //ipLabel.Text = ip;

                    //string year = (from x in db.monitoring_plan
                    //               where x.monitoring_plan_id == planID
                    //               select new { x.year.year1 }).First().year1.ToString();
                    //Label yrLabel = row.FindControl("YrLabel") as Label;
                    //yrLabel.Text = year;
                }
            }

            for (int intRowIndex = 0; intRowIndex < MonitoringGridView.Columns.Count; intRowIndex++)
            {
                TableCell tblCell = ((TableCell)MonitoringGridView.HeaderRow.Cells[intRowIndex]);
                //Select Which Columns to filter
                if (intRowIndex != 6 && intRowIndex < 8)
                {
                    tblCell.CssClass = "filter";
                    tblCell.Attributes.Add("alt", MonitoringGridView.Columns[intRowIndex].SortExpression);
                }

                if (objSelectedDataCollection.DataCollection != null)
                {
                    foreach (SelectedData selectedData in objSelectedDataCollection.DataCollection)
                    {
                        if ((selectedData.ColumnName == MonitoringGridView.Columns[intRowIndex].SortExpression) &&
                            (selectedData.SelectedValue.Count<string>() > 0))
                        {
                            if (intRowIndex != 0 && intRowIndex != 5 && intRowIndex != 9 && intRowIndex != 10 && intRowIndex != 11)
                            {
                                tblCell.CssClass = "filterExist";
                            }
                        }
                    }
                }
            }

            //============================================

            /*var MonitoringData = (from data in db.monitoring_plan select data);
            if (MonitoringData != null)
            {
                MonitoringGridView.DataSource = MonitoringData.ToList();
                MonitoringGridView.DataBind();
            }*/

            
        }

        protected void MonitoringGridView_RowEditing(object sender, GridViewEditEventArgs e)
        {
            MonitoringGridView.EditIndex = e.NewEditIndex;
            BindGrid();
        }

        protected void EditButton_Click(object sender, EventArgs e)
        {
            LinkButton btn = (LinkButton)(sender);
            //Label2.Text = btn.CommandArgument;
            Response.Redirect("~/Amkeni_Monitoring_Plan/AddNewIndicatorToActivity.aspx?activity=" + Server.UrlEncode(btn.CommandArgument));
        }

        protected void DelBtn_Click(object sender, EventArgs e)
        {
            LinkButton btn = (LinkButton)(sender);
            int planId = int.Parse(btn.CommandArgument.Trim());

            try
            {
                monitoring_plan delPlan = db.monitoring_plan.Where(data => data.monitoring_plan_id == planId).Single();

                var delInd = db.activity_indicator_connector.Where(data => data.monitoring_plan_id == delPlan.monitoring_plan_id);

                //============delete any indicator that is unreported and unassigned to another activity==========
                foreach (activity_indicator_connector _delInd in delInd)
                {
                    var delIndicator = from data in db.indicator_result
                                       where data.indicator_id == _delInd.indicator_id
                                       select data;
                    if (delIndicator == null || delIndicator.ToList().Count == 0)
                    {
                        var _delindicator = from data in db.activity_indicator_connector
                                            where data.indicator_id == _delInd.indicator_id
                                            select data;
                        if (_delindicator.ToList().Count == 1)
                        {
                            indicator delindicatorbyType = db.indicators.Where(data => data.indicator_id == _delInd.indicator_id && data.indicator_type_id == 2).Single();
                            db.indicators.Remove(delindicatorbyType);
                        }
                    }
                }
                //================================================================================================
                var _delPlanFreq = db.monitoring_data_collection_frequency_connector.Where(d => d.monitoring_plan_id == delPlan.monitoring_plan_id);
                foreach (monitoring_data_collection_frequency_connector delPlanFreq in _delPlanFreq)
                {
                    db.monitoring_data_collection_frequency_connector.Remove(delPlanFreq);
                }
                db.monitoring_plan.Remove(delPlan);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                db.SaveChanges();
                BindGrid();
            }
        }

        public string indicatorID(string _id)
        {
            int id = int.Parse(_id);
            string id_ = (from data in db.indicators where data.indicator_id == id select data.output_indicator_id).FirstOrDefault();
            if (id_ != null)
            {
                return id_;
            }
            else
            {
                return _id;
            }
        }
    }
}